package cn.wolfcode.web.interceptor;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.JsonResult;
import cn.wolfcode.domain.Permission;
import cn.wolfcode.util.RequiredPermission;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class CheckPermissionInterceptor implements HandlerInterceptor {

   //这个方法是在访问之前拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果是静态资源就以DefaultServlet结尾
        //如果是动态资源就以HandlerMethod结尾
        if (handler instanceof HandlerMethod){
            Employee emp = (Employee)request.getSession().getAttribute("USER_IN_SESSION");
            if (emp.isAdmin()){
                return true;
            }

            //得到方法
            HandlerMethod method=(HandlerMethod) handler;
            //得到贴在方法上的注解
            RequiredPermission methodAnnotation = method.getMethodAnnotation(RequiredPermission.class);
            if (methodAnnotation==null){
                return true;
            }

            //得到在登录拦截器里存在作用域里的该员工的所有权限
          List<Permission> Permissions  =  (List<Permission>)request.
                         getSession().getAttribute("PERMISSION_IN_SESSION");
          //遍历集合,看此员工的权限是否有访问这个方法的权限
            for (Permission p: Permissions){
                if (p.getExpression().equals(methodAnnotation.expression())){
                    return true;
                }

            }
            //看一下方法有没添加ResponseBody,以此来选择返回的结果
            ResponseBody methodAnnotation1 = method.getMethodAnnotation(ResponseBody.class);
            if (methodAnnotation1==null){
                response.sendRedirect("/nopermission");
            }else {
                //设置返回的编码方式,因为有中文所以要设置成utf-8
                response.setContentType("application/json;charset=utf-8");
                //因为是阿贾克斯请求所以要返回json字符串
                String data = JSON.toJSONString(new JsonResult(false, "没有该权限"));
                response.getWriter().write(data);

            }
         return false;
        }
        return true;
    }
}
